package com.test.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;

import org.apache.commons.codec.digest.DigestUtils;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.test.entity.FTPConfig;
import com.test.webapp.action.BaseAction;

/**
 * @author liuxl
 */
public class SFTPTool extends BaseAction {

	private static boolean reset = true;

	private static SFTPTool sftpTool = null;

	public static synchronized SFTPTool getInstance() {
		if (sftpTool == null) {
			sftpTool = new SFTPTool();
		}
		return sftpTool;
	}

	public static boolean cdDir(ChannelSftp sftp, String dir) {
		boolean isDirectory = true;
		try {
			sftp.cd(dir);
		}
		catch (SftpException e) {
			isDirectory = false;
		}
		return isDirectory;
	}

	/**
	 * 连接sftp服务器
	 * 
	 * @param host
	 *            主机
	 * @param port
	 *            端口
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return
	 */
	public static ChannelSftp connect(String host, int port, String username, String password) {
		ChannelSftp sftp = null;
		try {
			JSch jsch = new JSch();
			jsch.getSession(username, host, port);
			Session sshSession = jsch.getSession(username, host);
			sshSession.setPassword(password);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no");
			sshSession.setConfig(sshConfig);
			sshSession.connect();
			Channel channel = sshSession.openChannel("sftp");
			channel.connect();
			sftp = (ChannelSftp) channel;
		}
		catch (Exception e) {
			SFTPTool.reset = false;
		}
		return sftp;
	}

	/**
	 * 删除文件
	 * 
	 * @param directory
	 *            要删除文件所在目录
	 * @param deleteFile
	 *            要删除的文件
	 * @param sftp
	 */
	public static void delete(String directory, String deleteFile, ChannelSftp sftp) {
		try {
			sftp.cd(directory);
			sftp.rm(deleteFile);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 下载文件
	 * 
	 * @param directory
	 *            下载目录
	 * @param downloadFile
	 *            下载的文件
	 * @param saveFile
	 *            存在本地的路径
	 * @param sftp
	 */
	public static void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) {
		try {
			sftp.cd(directory);
			File file = new File(saveFile);
			sftp.get(downloadFile, new FileOutputStream(file));
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 方法说明。 <br>
	 * <p>
	 * 修改历史: 修改时间 修改人 <br>
	 * 修改说明 <br>
	 * 
	 * @param 参数名
	 *            参数说明
	 * @param fileAddress
	 * @param rPath
	 * @param fname
	 * @return
	 * @throws SftpException
	 * @return 返回结果说明
	 * @throws Exception
	 *             异常说明
	 */
	public static String ftp(String fileAddress, String rPath, String fname) throws SftpException {
		FTPConfig config = new FTPConfig();
		String ipAddress = config.getFTP_IPADDRESS();
		String path = config.getFTP_FILEADDRESS();
		String loginName = config.getFTP_LOGINNAME();
		String port = config.getFTP_PORT();
		String passWord = config.getFTP_LOGINPASSWORD();
		// String apachepath = config.getAPACHE_PATH();
		if (ipAddress != null) {
			String[] ip = ipAddress.split(";");
			if (ip != null) {
				for (int i = 0; i < ip.length; i++) {
					ChannelSftp csftp = SFTPTool.connect(ip[i], Integer.parseInt(port), loginName, passWord);
					if (SFTPTool.reset) {
						SFTPTool.upload(path, rPath, fileAddress + "/" + fname, csftp);
					}
					csftp.exit();
				}
			}
		}
		return rPath + fname;
	}

	/**
	 * 列出目录下的文件
	 * 
	 * @param directory
	 *            要列出的目录
	 * @param sftp
	 * @return
	 * @throws SftpException
	 */

	public static Map<String, Integer> listFiles(String directory)

	throws SftpException {
		System.err.println("dd:::==" + directory);
		Map<String, Integer> folder_file = new HashMap<String, Integer>();
		FTPConfig config = new FTPConfig();
		String ipAddress = config.getFTP_IPADDRESS();
		String loginName = config.getFTP_LOGINNAME();
		String port = config.getFTP_PORT();
		String passWord = config.getFTP_LOGINPASSWORD();
		if (ipAddress != null) {
			String[] ip = ipAddress.split(";");
			if (ip != null) {
				for (int i = 0; i < ip.length; i++) {
					ChannelSftp csftp = SFTPTool.connect(ip[i], Integer.parseInt(port), loginName, passWord);
					Vector vt = csftp.ls(directory);
					Iterator it = vt.iterator();
					while (it.hasNext()) {
						String n_str = it.next().toString();
						String[] ftp_v = n_str.split(" ");
						String name = ftp_v[ftp_v.length - 1];
						String type = ftp_v[0];
						if (!name.equals(".") && !name.equals("..")) {
							if (type.startsWith("d")) {
								folder_file.put(name, 1);
							} else {
								folder_file.put(name, 0);
							}
						}
					}
					csftp.exit();
					return folder_file;
				}
			}
		}
		return null;
	}

	public static void main(String[] args) throws SftpException {
		String pwd = DigestUtils.md5Hex("admin");
		System.err.println(pwd);
		// Map<String, Integer> map =
		// SFTPTool.listFiles("/data/www/cms.maoji.gov.cn");
		// if (!map.isEmpty()) {
		// Set set = map.keySet();
		// Iterator it = set.iterator();
		// while (it.hasNext()) {
		// String key = it.next().toString();
		// System.out.println(key + " * " + map.get(key));
		// }
		// }
	}

	/**
	 * 上传文件
	 * 
	 * @param directory
	 *            上传的目录
	 * @param uploadFile
	 *            要上传的文件
	 * @param sftp
	 * @throws SftpException
	 */
	public static String upload(String directory, String rPath, String uploadFile, ChannelSftp sftp) throws SftpException {
		try {
			sftp.cd(directory);
			String[] path_list = rPath.split("/");
			if (path_list != null) {
				for (int i = 0; i < path_list.length; i++) {
					if (!SFTPTool.cdDir(sftp, path_list[i])) {
						sftp.mkdir(path_list[i]);
						sftp.cd(path_list[i]);
					}
				}
			}
			File file = new File(uploadFile);
			sftp.put(new FileInputStream(file), file.getName());
		}
		catch (Exception e) {
			// log.error("@@@ Errors upload . "+e);
		}
		return sftp.pwd().toString();
	}

}
